package com.hqyj.system.shiro;

import com.hqyj.system.model.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import com.hqyj.system.service.PermissionService;
import com.hqyj.system.service.RoleService;
import com.hqyj.system.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.session.Session;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import com.hqyj.system.model.Permission;
import com.hqyj.system.model.Role;
import org.apache.shiro.authz.SimpleAuthorizationInfo;


import java.util.HashSet;
import java.util.List;

/**
 * @author cz
 * 2021/9/7 15:22
 */

public class CustomRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    public RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.认证
        // ---->第一步从token中取出身份信:token是用户输入的
        String username = (String) authenticationToken.getPrincipal();
        User user_db = null;
        System.out.println("--------------doGetAuthenticationInfo()-----------1-------------"+username);
        try {
            // 第二步（查询数据库）:根据用户输入的userCode从查询数据库
            user_db = userService.queryUserByUsername(username);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 如果查询不到返回null
        if (user_db == null) {
            return null;
        }
        System.out.println("--------------doGetAuthenticationInfo()-----------2-------------"+user_db);
        //获取当前用户的会话域
        Session session = SecurityUtils.getSubject().getSession();
        //保存Session中
        session.setAttribute("USER", user_db);
        //准备值
        String password = user_db.getPassword();
        //设置realm的名称
        String realmName = this.getName();
        //盐
        String salt = "1059";

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username,
                password, ByteSource.Util.bytes(salt), realmName);
        return simpleAuthenticationInfo;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //2.授权
        //拿到待授权的用户账号
        String username = (String) principalCollection.getPrimaryPrincipal();
        //根据待授权的用户账号：查询数据库相关用户授权信息
        //1.查询用户
        //查询数据库：按username
        User user = userService.queryUserByUsername(username);
        int userId = user.getUserId();

        //2.用户查询：用户相关的角色(roleListXZList)
        HashSet<String> roles = new HashSet<>();
        List<Role> roleListXZList = roleService.query_xz_roleByUserId(userId);
        for (Role role : roleListXZList) {
            roles.add(role.getRoleCode());
        }

        //3.用户查询：用户相关的权限(firstLvMenuList)
        HashSet<String> permissions = new HashSet<>();
        List<Permission> permissionListXZList = permissionService.queryloginUserPermission(userId);

        for (Permission permission : permissionListXZList) {
            permissions.add(permission.getPermissionCode());
        }

        //4.创建一个权限对象，收集角色和权限信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roles);
        info.addStringPermissions(permissions);
        return info;
    }
}
